package com.example.xianji.activity;

import java.text.SimpleDateFormat;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Change_phone_numberActivity extends Activity implements OnClickListener {
    public static String Change_Phone = "";
    private ImageView change_phone_number_back;
    private TextView text_change_phone, change_phone_title;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_message_yanzheng;
    private Button button_change_phone, yanzheng_button;
    private TimeCount mTimeCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__change_phone_number);
        //XJApplication.getInstance1().addActivity1(this);


        //XJApplication.getInstance().addActivity(this);
        change_phone_number_back = (ImageView) findViewById(R.id.change_phone_number_back);
        text_change_phone = (TextView) findViewById(R.id.text_change_phone);
        edittext_message_yanzheng = (EditText) findViewById(R.id.edittext_message_yanzheng);
        button_change_phone = (Button) findViewById(R.id.button_change_phone);
        yanzheng_button = (Button) findViewById(R.id.yanzheng_button);
        change_phone_title = (TextView) findViewById(R.id.change_phone_title);
        mTimeCount = new TimeCount(60000, 1000);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        text_change_phone.setText(getIntent().getStringExtra("phone"));
        if (getIntent().getIntExtra("isMobile", 0) == Contant.not_mobile) {
            //没有手机号的跳转过来新增手机号
            change_phone_title.setText("新增手机号");
        } else {
            //有手机号的跳转过来修改手机号
            change_phone_title.setText("修改手机号");
        }


        change_phone_number_back.setOnClickListener(this);
        button_change_phone.setOnClickListener(this);
        yanzheng_button.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.change_phone_number_back) {
            this.finish();
        } else if (v.getId() == R.id.button_change_phone) {
            if (edittext_message_yanzheng.getText().toString().length() == 0) {
                Toast.makeText(Main_Change_phone_numberActivity.this, "请填写验证码", Toast.LENGTH_SHORT).show();
            } else {
                Change_phone();
            }
        } else if (v.getId() == R.id.yanzheng_button) {
            mTimeCount.start();
            get_message_code();
        }
    }

    public void Change_phone() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (getIntent().getIntExtra("isMobile", 0) == Contant.not_mobile) {
            map.put("token", getIntent().getStringExtra("xianji_token"));
        } else {
            map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//            map.put("token", sp.getString("xianji_token", ""));
        }
        map.put("mobile", getIntent().getStringExtra("phone"));
        map.put("verify", edittext_message_yanzheng.getText().toString());

        JSONObject parmas = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.change_phone,
                parmas, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_CHANGE_PHONE, 1);
//                        ed.putInt("change_phone", 1);
//                        ed.commit();
                        Change_Phone = getIntent().getStringExtra("phone");//如果修改成功，就把现在的号码赋值；
                        Toast.makeText(Main_Change_phone_numberActivity.this, "新增成功,请点击'保存'按钮", Toast.LENGTH_SHORT).show();
                        //startActivity(new Intent(Main_Change_phone_numberActivity.this, Main_BianJi_XinxiActivity.class));
                        Main_Change_phone_numberActivity.this.finish();

                    } else {
                        Toast.makeText(Main_Change_phone_numberActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_message_code() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("code_from", "info");

        parms.addBodyParameter("mobile", getIntent().getStringExtra("phone"));
        parms.addBodyParameter("picverify", "");

        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_Change_phone_numberActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            yanzheng_button.setText("重新获取");
            yanzheng_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_style));
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                yanzheng_button.setText("60秒");
            }
            yanzheng_button.setText(str + "秒");
            yanzheng_button.setBackgroundDrawable(getResources().getDrawable(R.drawable.regiseter_huise_style));
        }
    }
}
